# 导入蓝图
from info.utils.image_storage import storage

from . import houses_blue
# 导入flask框架及其他
from flask import Blueprint,g,current_app,request,jsonify,session
# 导入模型类
from info.models import House,Facility,Area,Order,HouseImage
# 导入自定义错误类型
from info.utils.response_code import RET
# 导入装饰器
from info.utils.comments import login_required
# 导入数据库及常量参数
from info import db,constants
import time
from datetime import datetime,timedelta





# 发布房源
@houses_blue.route('/houses',methods=['POST'])
@login_required
def new_house():
    # 判断用户登录
    user =g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登陆')
    # 获取参数
    title = request.json.get("title")
    price = request.json.get('price')
    area_id = request.json.get("area_id")
    address = request.json.get('address')
    room_count = request.json.get('room_count')
    acreage = request.json.get('acreage')
    unit = request.json.get('unit')
    capacity = request.json.get('capacity')
    beds = request.json.get('beds')
    deposit = request.json.get('deposit')
    min_days = request.json.get('min_days')
    max_days = request.json.get('max_days')
    facility = request.json.get('facility')

    # 2校验参数，为空校验
    if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facility]):
        return jsonify(errno=RET.PARAMERR,errmsg='获取参数失败')

    #将facility列表中的字符串转成整形
    facilities = []
    for item in facility:
        new_facility = Facility.query.get(int(item))
        facilities.append(new_facility)

    # 创建房屋对象，设置属性
    house = House()
    house.user_id = g.user.id
    house.area_id = int(area_id)
    house.title = title
    house.price = int(price)
    house.address = address
    house.room_count = int(room_count)
    house.acreage = int(acreage)
    house.unit = unit
    house.capacity = int(capacity)
    house.beds = beds
    house.deposit = int(deposit)
    house.min_days = int(min_days)
    house.max_days = int(max_days)
    house.facilities = facilities
    # 提交数据到数据库
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')

    # 转化为字典列表
    data = {
        'house_id':house.id
    }

    # 返回数据给ajax
    return jsonify(errno=RET.OK,errmsg='OK',data=data)


# 上传房屋图片
@houses_blue.route('/houses/<int:house_id>/images',methods=['POST'])
@login_required
def house_image(house_id):
    # 判断用户是否登录
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    # 获取参数
    house_image = request.files.get('house_image')

    # 判断参数是否完整
    if not house_image:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        #读取图片为二进制数据上传
        image_name = storage(house_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.THIRDERR,errmsg="七牛云异常")
    if not image_name:
        return jsonify(error=RET.NODATA,errmsg="图片上传失败")

    # 根据房屋id获取房屋对象
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='房间对象获取失败')
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='无房间信息数据')

    if not house.index_image_url:
        house.index_image_url = image_name
        try:
            db.session.add(house)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='存储房间图片信息失败')
    else:
        houseImage = HouseImage()
        houseImage.house_id = house_id
        houseImage.url = image_name
        try:
            db.session.add(houseImage)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='存储房屋图片失败')

    data = {
        "url": constants.QINIU_DOMIN_PREFIX+image_name
    }
    # 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


# 3.5房屋详情页
@houses_blue.route('/houses/<int:house_id>')
@login_required
def houses_details(house_id):

    user = g.user
    # 判断
    try:
        house_details = House.query.get(house_id)
    except Exception as e:
        current_app.logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not house_details:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    data = {
        "user_id": g.user.id if user else -1,
        "house": house_details.to_full_dict()
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

@houses_blue.route('/areas')
def get_areas_list():
    """
    城区列表
    1.获取城区数据
    2.判断查询结果
    3.定义列表保存城区数据,拼接内容
    4.返回结果
    :return:
    """

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询城区数据失败')

    if not areas:
        return jsonify(errno=RET.NODATA,errmsg='无城区数据')
    areas_list = []
    for area in areas:
        areas_list.append(area.to_dict())

    return jsonify(errno=RET.OK,errmsg='OK',data=areas_list)

@houses_blue.route('/houses/index')
def get_index():

    """
    首页房屋推荐展示
    1.获取房屋数据
    2.判断查询结果
    3.定义列表保存房屋数据，拼接内容
    4.返回结果
    :return:
    """
    try:
        houses = House.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询房屋数据失败')
    if not houses:
        return jsonify(errno=RET.NODATA,errmsg='无房屋数据')
    houses_list = []
    for house in houses:
        houses_list.append(house.to_basic_dict())

    return jsonify(errno=RET.OK,errmsg='OK',data=houses_list)

@houses_blue.route('/houses')
def search_houses():

    # 获取请求参数,区域ID、开始居住时间、离开时间、排序方式、页数
    aid = request.args.get('aid','')
    sd = request.args.get('sd','')
    ed = request.args.get('ed','')
    sk = request.args.get('sk','new')
    p = request.args.get('p',1)

    # 检查参数
    # 日期
    try:
        # 入住日期
        sd_day = None
        if sd:
            sd_day = datetime.strptime(sd,'%Y-%m-%d')
        # 退房日期
        ed_day = None
        if ed:
            ed_day = datetime.strptime(ed,'%Y-%m-%d')
        if sd_day and ed_day:
            assert sd_day <= ed_day
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='日期参数错误')
    # 转换页数类型
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='页数类型错误')
    # 定义列表保存区域数据
    filter_params = []
    # 区域信息
    if aid:
        filter_params.append(House.area_id==aid)
    # 获取不冲突的房屋信息
    try:
        # 定义列表保存订单信息
        houses_order_list = []
        if sd_day and ed_day:
            houses_order_list = Order.query.filter(Order.begin_date<=ed_day,Order.end_date>=sd_day).all()
        elif sd_day:
            houses_order_list = Order.query.filter(Order.end_date>=sd_day).all()
        elif ed_day:
            houses_order_list = Order.query.filter(Order.begin_date<=ed_day)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    # 判断查询结果
    if houses_order_list:
        houses_id_list = [order.house_id for order in houses_order_list]
    #     添加查询条件，过滤不冲突的房屋
        filter_params.append(House.id.notin_(houses_id_list))


    # 查询房屋数据排序方式
    try:

        if sk == 'booking':
            paginate = House.query.filter(*filter_params).order_by(House.order_count.desc()).paginate(p, 5, False)

        elif sk == 'price-inc':
            paginate = House.query.filter(*filter_params).order_by(House.price.esc()).paginate(p, 5, False)

        elif sk == 'price-des':
            paginate = House.query.filter(*filter_params).order_by(House.price.desc()).paginate(p, 5, False)
        else:
            paginate = House.query.filter(*filter_params).order_by(House.update_time.desc()).paginate(p, 5, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据错误')

    # 判断查询结果
    if not paginate:
        return jsonify(errno=RET.NODATA,errmsg='无房屋数据')
    houses_data = paginate.items
    total_page = paginate.pages
    # 定义列表保存房屋信息
    houses = []
    for house in houses_data:
        houses.append(house.to_basic_dict())
    data = {
        'houses':houses,
        'total_page':total_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)





